<template>
    <div class="main">
        <div style="display: flex;height: 100%;">
            <div class="leftBox" style="width: 200px;height: 100%;">
                <div class="categoryTree" style="height: 100%;">
                    <p class="bg-primary-subtle text-secondary">
                        <span style="font-size: 12px;padding: 3px;">分类</span>
                    </p>
                    <el-tree class="scopeCss" style="height: 100%;overflow-y: auto;" :data="treeData"
                        default-expand-all></el-tree>
                </div>
            </div>
            <div class="rightBox" style="width: calc(100% - 210px);margin-left: 10px;">
                <el-form :model="search" :inline="true">
                    <el-form-item>
                        <el-input v-model="search.name" placeholder="名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="loadData" type="primary">搜索</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                        <el-button @click="openApiAdd" type="primary">新增</el-button>
                        <el-button @click="exportExcel" type="primary">导出</el-button>
                    </el-form-item>
                </el-form>
                <el-row style="height: calc(100% - 0px);">
                    <el-table height="100%" :data="dataList" border style="width: 100%;" :row-key="getRowKey"
                        ref="singleTable" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" :reserve-selection="true" />
                        <el-table-column type="expand">
                            <template #default="scope">
                                <div m="4">
                                    <div>{{ scope.row.info }}</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="code" label="编号" min-width="100">
                            <template #default="scope">
                                <el-link type="primary" @click="selectAndUpdate(scope.row)">
                                    {{ scope.row.code }}
                                </el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="名称" min-width="100" show-overflow-tooltip>
                            <template #default="scope">
                                {{ scope.row.name }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="downurl" label="下载地址" min-width="140" show-overflow-tooltip />
                        <el-table-column prop="categoryId" label="类型" min-width="60" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column prop="isHot" label="推荐">
                            <template #default="scope">
                                {{ scope.row.isHot ? '是' : '否' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="descs" label="描述" min-width="140" show-overflow-tooltip />
                        <el-table-column prop="isShow" label="展示">
                            <template #default="scope">
                                {{ scope.row.isShow ? '是' : '否' }}
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="display: flex;width: 100%;justify-content: center;">
                        <el-pagination small v-model:current-page.sync="page" v-model:page-size="pageSize"
                            :page-sizes="[1, 10, 20, 30, 50]" background layout="total, sizes, prev, pager, next, jumper"
                            :total="total" @size-change="loadData" @current-change="loadData" />
                    </div>
                </el-row>
            </div>
        </div>
    </div>

    <!-- 新增 -->
    <el-dialog v-model="apiDialog" title="add" width="80%" :align-center="true" @closed="closedApiDialog">
        <template #header>
            <span slot="title" class="dialogTitle1">新增</span>
        </template>
        <el-form :model="api" :rules="apiRefRules" ref="ApiRef" label-width="110" label-position="right"
            class="demo-ruleForm">
            <el-row>
                <el-col>
                    <el-form-item prop="name" label="名称">
                        <el-input v-model="api.name" placeholder="名称"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-form-item prop="downurl" label="下载地址">
                        <el-input v-model="api.downurl" placeholder="下载地址"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-form-item prop="imageUrl" label="封面">
                        <el-upload class="avatar-uploader"
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :show-file-list="false">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item prop="isHot" label="是否推荐">
                        <el-radio-group v-model="api.isHot">
                            <el-radio :label="true">是</el-radio>
                            <el-radio :label="false">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="isShow" label="是否对外显示">
                        <el-radio-group v-model="api.isShow">
                            <el-radio :label="true">是</el-radio>
                            <el-radio :label="false">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="isPay" label="限时免费">
                        <el-radio-group v-model="api.isPay">
                            <el-radio :label="true">是</el-radio>
                            <el-radio :label="false">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="categoryId" label="大类别">
                        <el-select v-model="api.categoryId" class="m-2" placeholder="Select">
                            <el-option :key="1" label="JAVA" :value="1" />
                            <el-option :key="2" label="视频" :value="2" />
                            <el-option :key="3" label="文档" :value="3" />
                            <el-option :key="4" label="HTML+CSS" :value="4" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="money" label="费用">
                        <el-input-number v-model="api.money" :precision="2" :step="0.1" :min="0" placeholder="费用" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="discount" label="折扣">
                        <el-input-number v-model="api.discount" :min="0" :max="10" :precision="1" :step="0.1"
                            controls-position="right" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item prop="sort" label="排序">
                        <el-input v-model="api.sort" placeholder="排序"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-form-item prop="descs" label="简介">
                        <el-input type="textarea" :autosize="{ minRows: 10 }" v-model="api.descs"
                            placeholder="描述"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeApiDialog">取消</el-button>
                <el-button :loading="loadingStatus" @click="saveApi" type="primary">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
export default {
    data() {
        return {
            page: 1,
            pageSize: 10,
            total: 0,
            loadingStatus: false,
            search: {
                name: null,
                isPay: null
            },
            treeData: [{
                id: 1, label: "JAVA", children: [
                    { id: 10, label: "JAVA基础API" }
                ]
            }, { id: 2, label: "HTML" }, { id: 3, label: "mybatis" }],
            dataList: [],
            apiDialog: false,
            api: {
                name: null,
                isPay: null,
                imageUrl: "",
                isHot: false,
                isShow: false,
                isPay: false,
                money: 0,
                discount: 10,
                sort: "",
                chapterList: []
            },
            apiRefRules: {
                name: [{ required: true, message: '必填' }],
                categoryId: [{ required: true, message: '必选' }],
            },
        }
    },
    created() {
        this.loadData()
    },
    methods: {
        handleSelectionChange(rows) {
            console.log(rows);
            this.selectTableRows = rows
        },
        loadData() {
            this.$axios.post(`/api/page/${this.page}/${this.pageSize}`, this.search).then(({ data }) => {
                if (data.code == 0) {
                    this.dataList = data.rows
                    this.total = data.total
                } else {
                    this.$message.error(data.msg)
                }
            }).catch(() => {
                this.$message.error("查询失败，请联系管理员！")
            })
        },
        getRowKey(row) {
            return row.id
        },
        resetSearch() {
            this.search = this.$options.data().search
            this.loadData()
        },
        selectLoadData() {
            this.search.isDelete = true
            this.loadData()
        },
        openApiAdd() {
            this.apiDialog = true
        },
        closeApiDialog() {
            this.$nextTick(() => {
                this.$refs.ApiRef.resetFields()
                // this.$refs.ApiRef.clearValidate()
                this.api = this.$options.data().api
            })
            this.apiDialog = false
        },
        closedApiDialog() {
            this.$nextTick(() => {
                this.$refs.ApiRef.resetFields()
                // this.$refs.ApiRef.clearValidate()
                this.api = this.$options.data().api
            })
        },
        saveApi() {
            this.loadingStatus = true
            this.$refs.ApiRef.validate((validateor) => {
                if (validateor) {
                    this.$axios.post("/api/saveAndChapter", this.api).then(({ data }) => {
                        if (data.code == 0) {
                            this.loadData()
                        } else {
                            this.$message.error(data.msg)
                        }
                    })
                    this.dataList.push(this.api)
                    this.loadingStatus = false
                    this.closeApiDialog()
                } else {
                    this.loadingStatus = false
                }
            })
        },
        selectAndUpdate(row) {
            this.$axios.get(`/api/getRowAndChapter/${row.id}`).then(({ data }) => {
                if (data.code == 0) {
                    if (!data.obj.platFrom) {
                        data.obj.system = []
                    }
                    this.api = data.obj
                    this.apiDialog = true
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        selectChapterContent(row) {
            this.$axios.get(`/api/getContent/${row.id}`).then(({ data }) => {
                if (data.code == 0) {
                    if (!data.obj.platFrom) {
                        data.obj.system = []
                    }
                    this.api = data.obj
                    this.apiDialog = true
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        saveContent() {
            if (!this.content.content) {
                this.$message.error("无内容！")
                return
            }
            if (!this.selectChapter.id) {
                this.$message.error("请先选择章节！")
                return
            }
            this.content.chapterId = this.selectChapter.id
            console.log(this.content);
            this.$axios.post(`/api/saveContent/`, this.content).then(({ data }) => {
                if (data.code == 0) {
                    this.$message.success(data.msg)
                } else {
                    this.$message.error(data.msg)
                }
            })
        },
        exportExcel() {
            this.downLoad("http://localhost:8899/excel/downLoadapiList", "XX分享.xlsx", "post")
        },
        downLoad(url, fileName, methodType = "get", params = null) {
            var xhr = new XMLHttpRequest()
            xhr.open(methodType, url)
            xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); //设置请求头(不同属性值传递的方式不同)
            xhr.responseType = 'blob'; //以blob的形式接收数据，一般文件内容比较大
            xhr.onload = function () {
                var content = this.response; //Blob数据
                var elink = document.createElement('a'); // 创建一个a标签用于下载
                elink.download = fileName; //规定被下载的超链接目标名字
                elink.style.display = 'none'; //标签隐藏
                var blob = new Blob([content]);
                elink.href = URL.createObjectURL(blob); //规定链接指向的页面的URL
                document.body.appendChild(elink);
                elink.click(); //原生dom触发
                document.body.removeChild(elink);
            };
            xhr.send(params); //post请求传的参数
        }
    }
}
</script>
<style scoped>
.el-dialog-div {
    height: 70vh;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}


/* // 滚动条宽度 */
.scopeCss::-webkit-scrollbar {
    width: 6px;
}

/* // 滚动条轨道 */
.scopeCss::-webkit-scrollbar-track {
    background: rgb(239, 239, 239);
    border-radius: 2px;
}

/* // 小滑块 */
.scopeCss::-webkit-scrollbar-thumb {
    background: #8ae77e3a;
    border-radius: 10px;
}

.scopeCss::-webkit-scrollbar-thumb:hover {
    background: #9fe77e;
}

.curos {
    cursor: pointer;
}

.curos:hover {
    background-color: #a2cddf7c;
}
</style>